package edu.sctu.yueding.activitys;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import edu.sctu.yueding.R;
import edu.sctu.yueding.adapter.PhotoSelectedGridViewAdapter;
import edu.sctu.yueding.config.CacheConfig;
import edu.sctu.yueding.config.URLConfig;
import edu.sctu.yueding.utils.CacheImgPathUtil;
import edu.sctu.yueding.utils.CompressImgUntil;
import edu.sctu.yueding.utils.JumpUtils;
import edu.sctu.yueding.utils.ProgressUtil;
import edu.sctu.yueding.utils.httputils.GetVolleyHttp;
import edu.sctu.yueding.utils.httputils.MultipartRequest;
import edu.sctu.yueding.utils.httputils.SharePreference;

/**
 * Created by 鑫爷您慢点 on 2016/8/3.
 */
public class UploadNewsActivity extends BaseActivity implements View.OnClickListener {
    private EditText mEditText;
    private String mEditTextString;
    private ImageView mChoseImg;
    private TextView mCancelTxt, mSubmitTxt;
    //    private LinearLayout lin;
    private GridView mGridView;
    private List<String> selectedImgPath = new ArrayList<String>();

    private SharePreference mSharePreferce;
    private CacheImgPathUtil mCacheImgPathUtil;
    private CallBackString callBackEditString;

    private Set<String> cacheImgPath = new HashSet<String>();

    private ProgressDialog mProgressDialog;

    private Activity mActivity;

    private CompressImgUntil compressImgUntil;

    private ProgressUtil progressUtil;


    public void setCallBackEditString(CallBackString callBackEditString) {
        this.callBackEditString = callBackEditString;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_news);
        initSystemBar(this, 0);
        initView();
        setSelectedImg();
    }

    private void setSelectedImg() {
        /**
         * 读取缓存中图片路径
         */
        cacheImgPath = mCacheImgPathUtil.getCacheImgPath();

        if (cacheImgPath.size() != 0) {
            mGridView.setVisibility(View.VISIBLE);
            for (String str : cacheImgPath) {
                selectedImgPath.add(str);
            }
        } else {
            mGridView.setVisibility(View.VISIBLE);
        }
        mGridView.setAdapter(new PhotoSelectedGridViewAdapter(UploadNewsActivity.this, selectedImgPath, mEditText));
    }

    private void initView() {

        mActivity = UploadNewsActivity.this;

        mEditText = (EditText) findViewById(R.id.id_upload_problem_edit_text);
        mChoseImg = (ImageView) findViewById(R.id.id_upload_news_chose_img_img);
        mCancelTxt = (TextView) findViewById(R.id.id_upload_news_back_txt);
        mSubmitTxt = (TextView) findViewById(R.id.id_upload_news_submit);

        mGridView = (GridView) findViewById(R.id.id_upload_news_chose_gridView);

        mCacheImgPathUtil = CacheImgPathUtil.getInstance(mActivity);
        mSharePreferce = SharePreference.getInstance(mActivity);


        progressUtil = ProgressUtil.getInstance(mActivity, "正在提交...");


        setEditTextContent();

        setEvent();


    }

    private void setEvent() {

        mEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String str = mEditText.getText().toString();
                if (!str.equals("")) {
                    mSharePreferce = SharePreference.getInstance(mActivity);
                    mEditTextString = mEditText.getText().toString();
                    mSharePreferce.setCache(CacheConfig.CACHE_UPLOAD_NEWS_TEXT, mEditTextString);
                }
            }
        });

        mCancelTxt.setOnClickListener(this);
        mSubmitTxt.setOnClickListener(this);
        mChoseImg.setOnClickListener(this);
    }

    /**
     * 根据缓存设置 editText的内容
     */
    private void setEditTextContent() {
        String cacheEditTextString = mSharePreferce.getString(CacheConfig.CACHE_UPLOAD_NEWS_TEXT);
        if (cacheEditTextString != null && !cacheEditTextString.equals("")) {
            mEditText.setText(cacheEditTextString);
        }
    }

    /**
     * 清除EditTextCache缓存
     */
    private void removeEditTextCache() {
        mSharePreferce.removeOneCache(CacheConfig.CACHE_UPLOAD_NEWS_TEXT);
    }

    private void removeSelectedNameCache() {
        mSharePreferce.removeOneCache(CacheConfig.CACHE_SELECTED_TEAM_NAME);
        mSharePreferce.removeOneCache(CacheConfig.CACHE_SELECTED_TEAM_ID);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_upload_news_chose_img_img:
                mEditText.setFocusable(false);
                /**
                 * 跳转 PhotoActivity
                 */
                Bundle bundle = new Bundle();
                bundle.putInt(PhotoActivity.FLAG, PhotoActivity.UPLOAD_TWEETS);
                JumpUtils.jumpActivity(this, PhotoActivity.class, bundle);

                finish();
                break;
            case R.id.id_upload_news_back_txt:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                boolean isOpen = imm.isActive();//isOpen若返回true，则表示输入法打开
                if (isOpen) {
                    /**
                     * 隐藏软键盘
                     */
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                            mActivity.getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
                mCacheImgPathUtil.removePathCache();
                removeEditTextCache();
                removeSelectedNameCache();
                finish();
                break;
            case R.id.id_upload_news_submit:

                mSubmitTxt.setClickable(false);
                Set<String> cacheImgPath = mCacheImgPathUtil.getCacheImgPath();
                String content = mEditText.getText().toString();
                if (cacheImgPath.size() == 0 && content.equals("")) {
                    Toast.makeText(mActivity, "请输入内容或选择图片", Toast.LENGTH_SHORT).show();
                } else {
                    mProgressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_SPINNER, false);
                    uploadQuestion(cacheImgPath);
                }

                break;
            default:
                break;
        }

    }


    private void uploadQuestion(Set<String> cacheImgPath) {
        /**
         * 读取缓存的登陆信息
         */
//        if (mSharePreferce.ifHaveShare(CacheConfig.CACHE_TOKEN)) {
        List<File> files = null;
        File tempFile;
        Map<String, String> map = new HashMap<String, String>();

        compressImgUntil = CompressImgUntil.getInstance();

        if (cacheImgPath.size() != 0 && cacheImgPath != null) {
            if (cacheImgPath.size() > 9) {
                mProgressDialog.dismiss();
                Toast.makeText(mActivity, "最多只能上传9张图片。", Toast.LENGTH_LONG).show();
            } else if (cacheImgPath.size() > 0) {

                files = new ArrayList<>();

                for (String path : cacheImgPath) {
                    UUID uuid = UUID.randomUUID();
                    String fileName = uuid + ".jpeg";

                    /**
                     * 压缩处理
                     */
                    compressImgUntil.compressImageByScale(path, CacheConfig.CACHE_HOME, fileName);

                    /**
                     * 读取压缩后图片
                     */
                    tempFile = new File(CacheConfig.CACHE_HOME + "/" + fileName);
                    files.add(tempFile);
                }


            }
        }


        if (cacheImgPath.size()  == 0){
            files = null;
        }
        map.put("content", mEditText.getText().toString());
        MultipartRequest multipartRequest = new MultipartRequest(URLConfig.URL_COMMUNITY_UPLOAD_TWEETS,
                errorListener,
                listener,
                "files",
                files,
                map,
                URLConfig.BEAREAR + mSharePreferce.getString(CacheConfig.CACHE_TOKEN));

        multipartRequest.setRetryPolicy(new DefaultRetryPolicy(120 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES
                , DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        GetVolleyHttp.getInstance(mActivity).uploadFiles(multipartRequest);

//        }
    }

    Response.Listener<String> listener = new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            compressImgUntil.recursionDeleteFile(new File(CacheConfig.CACHE_HOME));
            mProgressDialog.dismiss();
            Bundle bundle = new Bundle();
            bundle.putInt("flag", 2);
            mCacheImgPathUtil.removePathCache();
            removeSelectedNameCache();
            removeEditTextCache();
            JumpUtils.activityToFragmentJump(UploadNewsActivity.this, bundle);
            finish();
        }
    };
    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            mProgressDialog.dismiss();
//            Toast.makeText(mActivity, UrlConfig.NETWORK_ERROR_MESSAGE, Toast.LENGTH_SHORT);
        }
    };

    public interface CallBackString {
        void getString(String string);
    }

}
